/*
 * DBProcSendXMS.java
 *
 * Created on March 8, 2007, 4:05 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */
package wap.rockvilletech.xms;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

import org.apache.log4j.Logger;

import wap.rockvilletech.portal.ConnectionNotFoundException;

/**
 *
 * @author tazzix
 * @modified Usman
 */
public class DBProcSendXMS {

    private static final Logger log = Logger.getLogger(DBProcSendXMS.class);    
    private static DBProcSendXMS dbProc = null;
    private int connCount = 0;

    /** Creates a new instance of DBProcSendXMS */
    private DBProcSendXMS() {
    }

    public static DBProcSendXMS getInstance() {
        if (dbProc == null) {
            dbProc = new DBProcSendXMS();
        }
        return dbProc;
    }

    public Connection getDBConnection() throws ConnectionNotFoundException {
        Connection conn = null;
        try {
            Context initContext = new InitialContext();
            Context envContext = (Context) initContext.lookup("java:/comp/env");
            DataSource ds = (DataSource) envContext.lookup("jdbc/SendXMSDB");
            conn = ds.getConnection();
            connCount++;
        } catch (NamingException ex) {
            throw new ConnectionNotFoundException(ex);
        } catch (SQLException ex) {
            throw new ConnectionNotFoundException(ex);
        }
        return conn;
    }

    public void closeDBConnection(Connection conn) {
        if (conn != null) {
            try {
                conn.close();
                connCount--;
                conn = null;
            } catch (SQLException e) {
                log.error("Error closing connection, connCount:" + connCount, e);
            }
        }
    }

    public boolean saveXMS(String sendxms, String providerName) {
	    boolean status = false;
    	Connection con = null;
	    PreparedStatement pst = null;
	    try {
	        con = getDBConnection();
	        pst = con.prepareStatement("INSERT INTO spoolDir (provider, created, priority, xms) SELECT id, NOW(), 1, ? FROM providerId WHERE name=?");
	        int parameterIndex=1;
	        pst.setString(parameterIndex++, sendxms);
	        pst.setString(parameterIndex++, providerName);
	        int upc = pst.executeUpdate();
	        pst.close();
	        log.debug("saveXMS(" + providerName + ") done upCount=" + upc);
	        status = true;
	    } catch (Exception e) {
	        log.error("saveXMS(" + sendxms + ", " + providerName + ") ", e);
	    } finally {
	        closeDBConnection(con);
	    }
	    return status;
    }

}
